package cn.trigram.validation.annotation.validator;

import cn.trigram.validation.annotation.EnumValueCheck;
import java.lang.reflect.Method;
import java.util.Objects;
import javax.validation.ConstraintValidatorContext;

/**
 * EnumValueCheck校验器
 *
 * @version 1.0.0
 * @date 2023/05/09 15:51:42
 * @since 1.0.0
 */
public abstract class AbstractEnumValueValidator {

    private Class<? extends Enum<?>> enumClass;

    private Method valueMethod;

    private static final String METHOD_NAME = "getValue";

    public void initialize(EnumValueCheck constraintAnnotation) {
        enumClass = constraintAnnotation.value();
        try {
            // 先判断该enum是否实现了getValue方法
            valueMethod = enumClass.getDeclaredMethod(METHOD_NAME);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException("指定枚举类没有getValue方法", e);
        }
    }

    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果为空返回 true , 判空用 @NotNull 等专用注解
        if (Objects.isNull(value)) {
            return true;
        }
        try {
            if (!enumClass.isEnum()) {
                return true;
            }
            Enum[] enumConstants = enumClass.getEnumConstants();
            for (Enum e : enumConstants) {
                Object enumValue = valueMethod.invoke(e);
                if (Objects.equals(enumValue, value)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
